package com.mxpio.erp.technology.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.technology.entity.*;
import com.mxpio.erp.common.technology.service.*;
import com.mxpio.erp.common.technology.vo.ItemWithSubExtendsVO;
import com.mxpioframework.camunda.service.BpmnFlowService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.util.SecurityUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService {

    @Autowired
    private ItemLeadTimePropService itemLeadTimePropSerivce;
    @Autowired
    private ItemPlanPropService itemPlanPropSerivce;
    @Autowired
    private ItemPurchasePropService itemPurchasePropSerivce;
    @Autowired
    private ItemStorePropService itemStorePropSerivce;

    @Autowired
    private ItemMaterialPropService itemMaterialPropService;
    @Autowired
    private BpmnFlowService bpmnFlowService;

    @Override
    @Transactional(readOnly = true)
    public Result<ItemWithSubExtendsVO> queryItemWithExtendsByCode(String itemCode){
        Item item = getById(Item.class, itemCode);
        if (item==null){
            return Result.error("物料code未能匹配到数据！");
        }
        ItemWithSubExtendsVO extendsVO = new ItemWithSubExtendsVO();
        BeanUtils.copyProperties(item,extendsVO);

        ItemPropKey key = new ItemPropKey();
        key.setPropType("item");
        key.setCode(item.getItemCode());
        //关联物料子表扩展信息
        ItemLeadTimeProp itemLeadTimeProp = itemLeadTimePropSerivce.getById(ItemLeadTimeProp.class, key);
        extendsVO.setItemLeadTimeProp(itemLeadTimeProp);

        ItemPlanProp itemPlanProp = itemPlanPropSerivce.getById(ItemPlanProp.class, key);
        extendsVO.setItemPlanProp(itemPlanProp);

        ItemPurchaseProp itemPurchaseProp = itemPurchasePropSerivce.getById(ItemPurchaseProp.class, key);
        extendsVO.setItemPurchaseProp(itemPurchaseProp);

        ItemStoreProp itemStoreProp = itemStorePropSerivce.getById(ItemStoreProp.class, key);
        extendsVO.setItemStoreProp(itemStoreProp);

        ItemMaterialProp itemMaterialProp = itemMaterialPropService.getById(ItemMaterialProp.class, key);
        extendsVO.setItemMaterialProp(itemMaterialProp);
        return Result.OK(extendsVO);
    }

    @Override
    @Transactional
    public String deleteCheck(String itemCode) {
        String[] itemCodes = itemCode.split(",");
        StringBuilder msg = new StringBuilder();
        for(String key : itemCodes){
            //查询物料是否被bom引用
            List<BomInfo> bomInfos = JpaUtil.linq(BomInfo.class).equal("parentCode", key).list();
            if (CollectionUtils.isNotEmpty(bomInfos)){
                msg.append("物料【").append(key).append("】被Bom引用；");
            }
            //查询物料是否被bom明细引用
            List<BomInfo> bomInfoLineList = JpaUtil.linq(BomInfoLine.class).equal("itemCode", key).list();
            if (CollectionUtils.isNotEmpty(bomInfoLineList)){
                msg.append("物料【").append(key).append("】被Bom明细引用；");
            }
        }
        return msg.toString();
    }

    @Override
    @Transactional
    public Result<?> batchSubmit(List<Item> items) {
//        String[] itemCodeArr = itemCodes.split(",");
        for (Item item : items){
//            Item item = this.getById(Item.class, itemCode);
            //当传输过来的的审批状态为 审核，已审核时，进行校验
            String itemCodeBad = null;
            if (StringUtils.equals(item.getBpmnStatus(), OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                ||StringUtils.equals(item.getBpmnStatus(), OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
                if (itemCodeBad== null){
                    itemCodeBad = item.getItemCode();
                }else {
                    itemCodeBad = itemCodeBad + "," + item.getItemCode();
                }
            }
            if (itemCodeBad != null){
                return Result.error("物料编码【"+itemCodeBad+"】的状态为【审核中、已审核】的其一，不能进行重复提交操作");
            }
            String key ="item";
            String businessKey= item.getItemCode();
            String loginUsername = SecurityUtils.getLoginUsername();
            // 创建一个Map<String, Object>类型的实例
            Map<String, Object> properties = new HashMap<>();
            properties.put("bpmnStatus","01");
            properties.put("businessKey",item.getItemCode());
            properties.put("createBy",item.getCreateBy());
            properties.put("createDept",item.getCreateDept());
            properties.put("createTime",item.getCreateTime());
            properties.put("drawingNo",item.getDrawingNo());
            properties.put("itemCode",item.getItemCode());
            properties.put("itemGroupCode",item.getItemGroupCode());
            properties.put("itemName",item.getItemName());
            properties.put("itemSource",item.getItemSource());
            properties.put("lifeCycle",item.getLifeCycle());
            properties.put("material",item.getMaterial());
            properties.put("saleAble",item.getSaleAble());
            properties.put("saveTransient","true");
            properties.put("scale",item.getScale());
            properties.put("unitCode",item.getUnitCode());
            properties.put("virtualPart",item.getVirtualPart());
            //发起工作流
            ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);

            //回写数据
            item.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode());
            item.setProcessInstanceId(processInstance.getId());
            this.update(item);
        }
        return Result.OK("提交成功");
    }
}
